import { FC, useEffect } from "react"
import { useRoutes, useNavigate, useLocation } from "react-router-dom"
import useStorage from "./useStorage"
//定义类型

interface Iprops {
    routes: RouteObj[]; //routes配置
    tokenKey: string //token的key
}

const useRouteWithGuard: FC<Iprops> = (props) => {

    //数据的解构
    let { routes, tokenKey } = props;

    //根据传入的tokenKey从本地获取token

    //如果关闭页面就要退出登入 那么就把token存到sessionStorage

    //我们现在默认存到本地localstorage

    let [token, methods] = useStorage('qf-token');
    //获取当前访问的路径

    let location = useLocation();
    // console.log(location)

    //编程式导航的方法
    let navigate = useNavigate()
    //判断有没有token

    useEffect(() => {
        if (!token) {
            //访问的页面是不是登入页
            if (location.pathname !== '/login') {
                //跳转到登入页
                navigate('/login')
            }
        }
    }, [location])

    let element = useRoutes(routes)

    return element

}

export default useRouteWithGuard;